//
//  PicturePickerController.swift
//  01-发布图片测试
//
//  Created by 白利兵 on 15/11/2.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
//import SnapKit
// 照片选择控制器制作步骤
// 1. 初始化流式布局(包括大小，间距（行，个体之间），列数，滚动方向？，)
// 2. 注册可重用cell
// 3. 数据源方法和代理方法
// 4. 自定义cell - 注册可重用标示符，懒加载控件，自动布局，数据模型
// 5. 图片数组（可变）

let picturePickerCellReuseId = "picturePickerCellReuseId"
class PicturePickerController: UICollectionViewController {
    var picWidth: CGFloat = 0
    let colums: CGFloat = 4
    let margin: CGFloat = UIScreen.mainScreen().scale * 4
    // 定义一个图片索引
    var selectedIndex = 0
    // 设置添加最大照片数量
    let maxImageCount = 8
    // 定义一个图片数组
    var pictures = [UIImage]()
    // MARK: - 构造方法
    init(){
        // 初始化布局
        let flowLayout = UICollectionViewFlowLayout()
        // 设置布局属性
        let width = (UIScreen.mainScreen().bounds.width - (colums + 1)*margin)/colums
        picWidth = width
        flowLayout.itemSize = CGSizeMake(width, width)
        flowLayout.minimumInteritemSpacing = margin
        flowLayout.minimumLineSpacing = margin
        flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical
        // 重写父类方法
        super.init(collectionViewLayout: flowLayout)
        // 注册可重用cell
        collectionView?.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: picturePickerCellReuseId)
        // 设置数据源
        collectionView?.dataSource = self
        //pictures.append(UIImage(named: "tabbar_compose_icon_add")!)
        // 设置背景色
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - 数据源方法 UICollectionViewDataSource
extension PicturePickerController:PicturePickerCellDelegate {
    // MARK: 返回多少项
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count < maxImageCount ? pictures.count + 1 : pictures.count
    }
    // MARK: 返回怎样的cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 从缓存池中获取cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(picturePickerCellReuseId, forIndexPath: indexPath) as! PicturePickerCell
        // 设置cell数据 TODO
        cell.delegate = self
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        return cell
    }
}
// MARK: - UIImagePickerControllerDelegate代理方法
extension PicturePickerController:UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    // 完成照片选择后的回调
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        // 获取照片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.scaleToWith(600)
        // 把照片添加到数组中
        pictures.append(scaleImage)
        // 刷新数据源
        collectionView?.reloadData()
        // 关闭当前控制器
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    // 取消按钮点击后的回调
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
       // 关闭当前控制器
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}
// MARK: - PicturePickerCellDelegate代理方法
extension PicturePickerController {
    @objc private func PicturePickerCellDidAdd(cell: PicturePickerCell) {
        // 跳转到照片控制器
//        print("跳转到照片控制器")
        // 判断是否允许访问相册
        /**
        PhotoLibrary            保存的照片(可以删除) + 同步的照片(不允许删除)
        SavedPhotosAlbum        保存的照片/屏幕截图/拍照
        */
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("无法访问照片库")
            return
        }
        
        // 创建控制器
        let imagePickerVC = UIImagePickerController()
        // 设置代理
        imagePickerVC.delegate = self
        // 跳转到控制器
        self.presentViewController(imagePickerVC, animated: true, completion: nil)
    }
    @objc private func PicturePickerCellDidDelete(cell: PicturePickerCell) {
        // 删除图片
//        print("删除图片")
        // 获取索引
        let indexPath = collectionView?.indexPathForCell(cell)
        selectedIndex = (indexPath?.item)!
        // 把当前图片从数组中移除
        pictures.removeAtIndex(selectedIndex)
        // 刷新数据
        collectionView?.reloadData()
    }
}
/// MARK: PicturePickerCellDelegate
@objc private protocol PicturePickerCellDelegate: NSObjectProtocol {
    // MARK: - 添加图片
    optional func PicturePickerCellDidAdd(cell: PicturePickerCell)
    // MARK: - 删除图片
    optional func PicturePickerCellDidDelete(cell: PicturePickerCell)
    
}
// MARK: - 自定义cell
private class PicturePickerCell: UICollectionViewCell {
    // 模型数据，重写set方法
    var image: UIImage? {
        didSet{
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            deleteButton.hidden = (image == nil  ? true : false)
            addButton.userInteractionEnabled = (image == nil  ? true : false)
        }
    }
    // 设置代理属性
    weak var delegate: PicturePickerCellDelegate?
    // MARK: - 懒加载控件
    // 添加按钮
    private var addButton: UIButton = {
            let button = UIButton()
            button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            return button
        }()
    
    // 删除按钮（刚开始隐藏，有图片时才显示）
    private var deleteButton: UIButton = {
            let button = UIButton()
            button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
            return button
        }()
    
    // MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
       
        // 设置UI
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
// MARK: - 设置UI
extension PicturePickerCell {
    
    // MARK: - 设置UI
    private func setupUI() {
        // 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        addButton.frame = bounds
        deleteButton.hidden = true
        // 设置图片填充方式
        addButton.imageView?.contentMode = .ScaleAspectFill
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        //  MARK: - 添加监听事件
        addButton.addTarget(self, action: "addPicture", forControlEvents: UIControlEvents.TouchUpInside)
        deleteButton.addTarget(self, action: "deletePicture", forControlEvents: UIControlEvents.TouchUpInside)
    }
    // MARK: - 监听事件
    @objc private func addPicture() {
        // 代理响应添加事件
        delegate?.PicturePickerCellDidAdd?(self)
    }
    @objc private func deletePicture() {
        // 代理响应删除事件
        delegate?.PicturePickerCellDidDelete?(self)
    }
}
































































